package com.css.fxfzfxqh.modules.getTemplate.controller;

import com.css.fxfzfxqh.modules.getTemplate.entity.FileName;
import com.css.fxfzfxqh.util.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;

@RestController
@RequestMapping("/template")
@Slf4j
public class TemplateController {

//    @Value("${templatePath}")
    private String templatePath;

    @PostMapping(value = "/download", produces = "text/html;charset=UTF-8")
    public void downloadExcel1( @RequestBody FileName fileName, HttpServletResponse response) throws FileNotFoundException {
        String file_name = fileName.getFileName();
//        String path =  ResourceUtils.getURL("classpath:template").getPath();
        String path =  templatePath;
        FileUploadUtil.download(path + File.separator + file_name, response);
    }
//    public void downloadExcel1( @RequestBody FileName fileName, HttpServletResponse response) {
//        log.info("入参: 模板名全称", fileName.getFileName());
//        try {
//            //请求头的模板名为中文
////            String file_name = URLEncoder.encode(fileName.getFileName(), "UTF-8");
//            String file_name = fileName.getFileName();
//            response.setHeader("content-Type", "application/vnd.ms-excel");
//            response.setHeader("Content-disposition", "attachment;fileName=" + file_name);
//            response.setContentType("application/x-download");
//            //获取文件的路径
//            String path = getClass().getResource("/template/" + fileName.getFileName()).getPath();
//            //路径名转换中文
//            String filePath = URLDecoder.decode(path, "utf-8");
//            FileInputStream inputStream = new FileInputStream(filePath);
//            OutputStream outputStream = response.getOutputStream();
//            byte[] bytes = new byte[65536];
//            int len;
//            while ((len = inputStream.read(bytes)) != -1) {
//                outputStream.write(bytes, 0, len);
//            }
//            outputStream.flush();
//            outputStream.close();
//            inputStream.close();
//            log.info(fileName.getFileName() + ": 模板下载完成");
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error(fileName.getFileName() + ":" + e);
//        }
//    }
}
